<template>
  <AxiomDialog
    :model-value="visible"
    :title="title"
    width="500px"
    @close="handleClose"
    @cancel="handleClose"
    @confirm="handleConfirm"
    :confirm-loading="loading"
  >
    <AxiomForm :model="form" :rules="rules" ref="formRef" label-width="100px">
      <AxiomFormItem label="角色名称" prop="role_name">
        <AxiomInput v-model="form.role_name" placeholder="请输入角色名称" />
      </AxiomFormItem>
      <AxiomFormItem label="角色标识" prop="role_code">
        <AxiomInput v-model="form.role_code" placeholder="请输入角色标识" :disabled="isEdit" />
      </AxiomFormItem>
      <AxiomFormItem label="描述" prop="description">
        <AxiomInput v-model="form.description" type="textarea" placeholder="请输入角色描述" />
      </AxiomFormItem>
    </AxiomForm>
  </AxiomDialog>
</template>

<script setup>
import { ref, reactive, computed, watch, inject } from 'vue';
import {
  AxiomDialog,
  AxiomFormItem,
  AxiomInput,
  AxiomForm,
} from 'axiom-view';
import { createRole, updateRole } from '@/api/system/role';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  mode: {
    type: String,
    default: 'add', // 'add' or 'edit'
  },
  initialData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['close', 'success']);
const { notification } = inject('axiom-utils');
const formRef = ref(null);

const loading = ref(false);
const form = reactive({});

const rules = reactive({
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  role_code: [{ required: true, message: '请输入角色标识', trigger: 'blur' }],
});

const isEdit = computed(() => props.mode === 'edit');
const title = computed(() => (isEdit.value ? '编辑角色' : '新增角色'));

// [修复] 监听 initialData 的变化，以更可靠地重置或填充表单
watch(() => props.initialData, (newData, oldData) => {
  // 仅在对话框可见时操作，避免不必要地更新
  if (!props.visible) return;

  // 从无到有 (新增) 或从有到无 (切换到新增)
  if (!newData) {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    // 手动清空，以防 resetFields 失效
    Object.keys(form).forEach(key => delete form[key]);
    return;
  }

  // 从一个数据切换到另一个数据 (编辑)
  Object.assign(form, newData);
}, { deep: true });


watch(() => props.visible, (val) => {
  if (val) {
    // [修复] 当对话框从不可见变为可见时，确保表单状态与 initialData 同步
    // 这是为了处理初次打开对话框的场景
    if (props.initialData) {
      Object.assign(form, props.initialData);
    } else {
      if (formRef.value) formRef.value.resetFields();
      Object.keys(form).forEach(key => delete form[key]);
    }
  }
});

const handleClose = () => {
  // 关闭时不再需要 resetFields，因为状态由父组件的 initialData 驱动
  emit('close');
};

const handleConfirm = async () => {
  try {
    if (!formRef.value) return;
    await formRef.value.validate();
    loading.value = true;

    const payload = { ...form };

    if (isEdit.value) {
      const updatePayload = {
        role_name: payload.role_name,
        description: payload.description,
      };
      await updateRole(payload.id, updatePayload);
      notification.success({ title: '成功', message: '更新成功' });
    } else {
      await createRole(payload);
      notification.success({ title: '成功', message: '新增成功' });
    }

    emit('success');
    handleClose();
  } catch (error) {
    // [最终修复] 只记录 error.message，以避免将复杂的 error 对象传递给可能被重写过的 console.error，从而防止 TypeError 崩溃
    console.error('表单提交失败:', error.message);
  } finally {
    loading.value = false;
  }
};
</script> 